<?php

namespace common\models\batch;


use common\models\User;
use yii\base\Model;

class UserBatch extends Model
{
    public $batch;

    public $doBatch;

    public $id;

    public function rules()
    {
        return [
            [['batch', 'doBatch', 'id'], 'required'],
            ['id', 'isIds'],
        ];
    }

    public function actions()
    {
        static $actions;

        if (isset($actions)) {
            return $actions;
        }

        $actions = [
            'block' => '禁止选中用户',
            'unblock' => '解禁选中用户',
            'delete' => '删除选中用户',
        ];

        $roleList = User::getRoleList();
        $addKey = '为选中的用户添加角色';
        $removeKey = '为选中的用户删除角色';

        foreach ($roleList as $name => $description) {
            $actions[$addKey]['add_role-' . $name] = $description;
            $actions[$removeKey]['remove_role-' . $name] = $description;
        }
        return $actions;
    }

    public function isIds($attribute, $params)
    {
        $value = $this->$attribute;
        if (!is_array($value)) {
            $this->addError('id', 'id invalid');
        }
    }

    public function process($id, $data)
    {
        $this->id = $id;

        if (!$this->load($data) || !$this->validate()) {
            return false;
        }

        if ($this->doBatch) {
            switch ($this->batch) {
                case 'block':
                    User::updateAll(['status' => User::STATUS_DELETED], ['id'=>$this->id]);
                    break;
                case 'unblock':
                    User::updateAll(['status' => User::STATUS_ACTIVE], ['id'=>$this->id]);
                    break;
            }

            if (($pos = strpos($this->batch, 'add_role-')) !== false) {
                $roleName = substr($this->batch, 9);
                if ($roleName) {
                    foreach (User::findAll(['id' => $this->id]) as $model) {
                        $model->addRole($roleName);
                    }
                }
            } elseif (($pos = strpos($this->batch, 'remove_role-')) !== false) {
                $roleName = substr($this->batch, 12);
                if ($roleName) {
                    foreach (User::findAll(['id' => $this->id]) as $model) {
                        $model->removeRole($roleName);
                    }
                }
            }
            return '应用已执行。';
        }

        return true;
    }
}